//
//  HRDynamicInfoViewController.m
//  Hear
//
//  Created by mac on 2017/4/11.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRDynamicInfoViewController.h"
#import "HRBaseTableView.h"
#import "HRDynamicInfoTableViewModel.h"
#import "HRDynamicInfoHeadView.h"
#import "HRDunamicLayout.h"
#import "HRDynamicInfoViewModel.h"
#import "HRDynamicCommentModel.h"
#import "HRGetLikesModel.h"
#import "MJRefresh.h"
#import "HRUpdataUserInfoModel.h"
#import "HRShowRecordView.h"
#import "HRRecordAudioViewController.h"
#import "HRUMShareTool.h"
#import "EaseChatToolbar.h"
#import "OSSImageUploader.h"
#import "EMVoiceConverter.h"
//#import "MyPlayTool.h"
#import "HRDynamicViewController.h"
@interface HRDynamicInfoViewController ()<UIAlertViewDelegate,EMChatToolbarDelegate>
@property (nonatomic, strong)HRBaseTableView *tableView;
@property (nonatomic, strong)HRDynamicInfoTableViewModel *tableViewModel;
@property (nonatomic, strong)HRDynamicInfoHeadView *headView;
@property (nonatomic, strong)HRDynamicInfoViewModel *viewModel;
@property (nonatomic, strong)HRDunamicLayout *myLayout;
@property (nonatomic, strong)HRGetLikesModel *likesModel;
@property (nonatomic, assign)NSInteger pIndex;

/*!
 @property
 @brief 底部输入控件
 */
@property (strong, nonatomic) UIView *chatToolbar;


/*!
 @property
 @brief 底部表情控件
 */
@property(strong, nonatomic) EaseFaceView *faceView;

/*
 @property
 @brief 底部录音控件
 */
@property(strong, nonatomic) EaseRecordView *recordView;

@property (weak, nonatomic) id<EaseMessageViewControllerDataSource> dataSource;
@property (weak, nonatomic) id<EaseMessageViewControllerDelegate> delegate;

@end

@implementation HRDynamicInfoViewController

-(HRGetLikesModel *)likesModel{
    if (_likesModel == nil){
        _likesModel = [HRGetLikesModel new];
    }
    return _likesModel;
}

-(HRDynamicInfoViewModel *)viewModel{
    if (!_viewModel){
        _viewModel = [HRDynamicInfoViewModel new];
    }
    return _viewModel;
}

-(HRDynamicInfoHeadView *)headView{
    if (!_headView){
        WeakSelf
        _headView = [[HRDynamicInfoHeadView alloc] initWithFrame:CGRectMake(0, 0, kFullWidth, self.myLayout.cellHeight)];
        _headView.layout = self.myLayout;
        _headView.likeButtonClickBlock = ^(BOOL isLike){
            [weakSelf getDynamicLike:isLike];
        };
        _headView.playMedioBlock = ^(HRDynamicModel *dynamicModel){
            HRDunamicLayout *layout = [[HRDunamicLayout alloc] initWithStatus:dynamicModel style:HRLayoutStyleDetail];
            weakSelf.headView.layout = layout;
        };
    }
    return _headView;
}

-(HRDynamicInfoTableViewModel *)tableViewModel{
    if (!_tableViewModel){
        WeakSelf
        _tableViewModel = [HRDynamicInfoTableViewModel new];
        _tableViewModel.deleteCommentBlock = ^(NSUInteger index){
            [weakSelf deleteCommentIndex:index];
        };
        _tableViewModel.iconTapBock = ^(NSString *currentUserID){
            HRDynamicViewController *VC = [HRDynamicViewController new];
            VC.currentUserID = currentUserID;
            [weakSelf.navigationController pushViewController:VC animated:YES];
        };
    }
    return _tableViewModel;
}

-(instancetype)init
{
    self = [super init];
    self.tableView = [HRBaseTableView new];
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    self.title = @"详情";
    
    self.dynamicModel.isPlaying = NO;
    self.myLayout = [[HRDunamicLayout alloc] initWithStatus:self.dynamicModel style:HRLayoutStyleDetail];

    
    
    [self.view addSubview:self.tableView];
    
    [self.tableViewModel handleWithTable:self.tableView];

    self.tableView.tableHeaderView = self.headView;
    
//    UIButton *leftButton = [UIButton buttonWithType:0];
//    leftButton.size = CGSizeMake(20, 20);
//    [leftButton setImage:[UIImage imageNamed:@"Back-Arrow"] forState:UIControlStateNormal];
//    [leftButton addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
//    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    UIButton *deleteButton = [UIButton buttonWithType:0];
    deleteButton.size = CGSizeMake(40, 20);
    deleteButton.titleLabel.font = CustomUIFont(13);
    [deleteButton setTitle:@"删除" forState:0];
    [deleteButton addTarget:self action:@selector(deleteClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:deleteButton];
    
    
    
    
   
    if (![self.myLayout.dynamicModel.UserLocalId isEqualToString:USERID]){
        deleteButton.hidden = YES;
    }else{
        self.navigationItem.rightBarButtonItems = @[rightItem];

    }
    
    
    WeakSelf
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view).offset(-46);
    }];
    CGFloat chatbarHeight = [EaseChatToolbar defaultHeight];
    self.chatToolbar = [[EaseChatToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - chatbarHeight, self.view.frame.size.width, chatbarHeight) type:HRDynamicComment];
    self.chatToolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    
    //Initializa the gesture recognizer
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyBoardHidden:)];
    [self.view addGestureRecognizer:tap];
    

    
    
    [self getCommentList];
    [self setupEmotion];

    
    
}



- (void)getCommentList{
    self.pIndex = 0;
    
    [self getCommentList:YES];
    WeakSelf
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pIndex = 0;
        [self getCommentList:YES];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
    
    //    //上拉加载
    self.tableView.mj_footer=[MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.pIndex ++;
        [weakSelf getCommentList:NO];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}


- (void)getCommentList:(BOOL)isHead{
    
    WeakSelf
    
    HRDynamicGetCommentRequestModel *requestModel = [HRDynamicGetCommentRequestModel new];
    requestModel.momentLocalId = weakSelf.myLayout.dynamicModel.LocalId;
    requestModel.pageSize = 10;
    requestModel.pageIndex = self.pIndex;
    requestModel.currentUserLocalId = USERID;
    
    [self.viewModel getCommentListParam:requestModel isSeccess:^(NSArray *commentArr) {
        if (isHead){
            [weakSelf.tableViewModel.contentArray removeAllObjects];
        }
        [weakSelf.tableViewModel.contentArray addObjectsFromArray:commentArr];
        [weakSelf.tableView reloadData];
        if (commentArr.count < requestModel.pageSize){
            weakSelf.tableView.mj_footer.hidden = YES;
        }else{
            
            weakSelf.tableView.mj_footer.hidden = NO;
        }
    }];
}




#pragma 点赞
- (void)getDynamicLike:(BOOL)isLike{
    
    WeakSelf
    
    if (isLike){
        [weakSelf.likesModel getLikeRequest:@{@"MomentLocalId":_dynamicModel.LocalId,@"LocalId":_dynamicModel.LocalId,@"UserLocalId":USERID,@"CreateTime":[self getCurrentTime]} isSeccess:^(BOOL isSeccess) {
            if(isSeccess){
                self.myLayout.dynamicModel.LikeCount = self.myLayout.dynamicModel.LikeCount+1;
                self.myLayout.dynamicModel.IsLike = @"1";
            }
        }];
//        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
//        
//        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
//            
//        });

    }else{
        [weakSelf.likesModel getDeletLikeRequest:@{@"MomentLocalId":_dynamicModel.LocalId,@"UserLocalId":USERID} isSeccess:^(BOOL isSeccess) {
            if (isSeccess){
                if (self.myLayout.dynamicModel.LikeCount){
                    self.myLayout.dynamicModel.LikeCount = self.myLayout.dynamicModel.LikeCount-1;
                }
                self.myLayout.dynamicModel.IsLike = @"0";
            }
        }];
//        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
//        
//        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
//            
//        });
    }
}

- (NSString *)getCurrentTime
{
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}

#pragma 删除帖子
- (void)deleteClick{
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定删除该动态？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertView.alertViewStyle=UIAlertViewStyleDefault;
    
    [alertView show];
   
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1){
        [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"cacheTime"];
        WeakSelf
        [self.viewModel deleteDynamic:@{@"LocalId":self.myLayout.dynamicModel.LocalId,@"UserLocalId":self.myLayout.dynamicModel.UserLocalId} isSeccess:^(BOOL isSeccess) {
            if (isSeccess){
                if (weakSelf.reloadListBlock){
                    weakSelf.reloadListBlock();
                }
                [MBProgressHUD showMessage:@"删除成功" finishBlock:nil];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
        }];
    }
}


- (void)deleteCommentIndex:(NSUInteger)index{
    HRDynamicCommentModel *model = self.tableViewModel.contentArray[index];
    [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"cacheTime"];

    WeakSelf
    if ([model.UserLocalId isEqualToString:USERID]){
        [self.viewModel deleteComment:@{@"LocalId":model.LocalId,@"UserLocalId":USERID} isSeccess:^(BOOL isSeccess) {
            if (isSeccess){
                [weakSelf.tableViewModel.contentArray removeObjectAtIndex:index];
                [weakSelf.headView.contenView.toolView.messageButton setTitle:[NSString stringWithFormat:@"  %ld",weakSelf.tableViewModel.contentArray.count] forState:0];

                [weakSelf.tableView reloadData];
                [MBProgressHUD showMessage:@"删除成功" finishBlock:nil];
            }
        }];
    }
}




#pragma 评论
- (void)answerComment:(NSString *)contentStr andType:(NSString *)type andUrlLength:(NSString *)urlLength{
    
    
    
    
    WeakSelf
//    if(![[[NSUserDefaults standardUserDefaults]objectForKey:@"SoundUrl"] length]){
//        [HRShowRecordView showRecordView:^{
//            HRRecordAudioViewController *recordVC = [HRRecordAudioViewController new];
//            recordVC.jz_navigationBarBackgroundHidden = YES;
//            recordVC.isSound = YES;
//            [weakSelf.navigationController pushViewController:recordVC animated:YES];
//        }];
//        return;
//    }
    
    
    if ([type isEqualToString:@"2"]){
        [OSSImageUploader asyncUploadSound:@[contentStr] complete:^(NSArray<NSString *> *names, UploadImageState state) {
            if (state == UploadImageFailed) return ;
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf postAnswerComment:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,[names firstObject]] andType:type andUrlLength:urlLength];
            });
        }];
    }else{
        [weakSelf postAnswerComment:contentStr andType:type andUrlLength:urlLength];
    }
}

- (void)postAnswerComment:(NSString *)contentStr andType:(NSString *)type andUrlLength:(NSString *)urlLength{
    WeakSelf
    
    HRDynamicCommentRequestModel *requestModel = [HRDynamicCommentRequestModel new];
    requestModel.LocalId = USERID;
    requestModel.UserLocalId = USERID;
    requestModel.MomentLocalId = weakSelf.myLayout.dynamicModel.LocalId;
    requestModel.CommentText = contentStr;
    
    requestModel.IsRead = 0;
    requestModel.ReplyUserLocalId = @"";
    requestModel.CreateTime = [weakSelf getCurrentTime];
    requestModel.CommentType = type;
    requestModel.SoundLength = urlLength;
    requestModel.SoundUrl = contentStr;
    if ([type isEqualToString:@"2"]){
        requestModel.CommentText = @"";
    }else{
        requestModel.SoundLength = @"0";
        requestModel.SoundUrl = @"";
    }
    [weakSelf.viewModel postDynamicCommentParam:requestModel AndCommentModel:^(HRDynamicCommentModel *commentModel) {
        weakSelf.myLayout.dynamicModel.CommentCount += 1;
        
        [weakSelf.headView.contenView.toolView.messageButton setTitle:[NSString stringWithFormat:@"  %ld",(long)weakSelf.myLayout.dynamicModel.CommentCount] forState:0];
        
        [weakSelf getCommentList:YES];
        
        
        [MBProgressHUD showMessage:@"评论成功" finishBlock:nil];
    }];
}



-(void)keyBoardHidden:(UITapGestureRecognizer *)tapRecognizer
{
    if (tapRecognizer.state == UIGestureRecognizerStateEnded) {
        [self.chatToolbar endEditing:YES];
    }
}

- (void)clickBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setChatToolbar:(EaseChatToolbar *)chatToolbar
{
    [_chatToolbar removeFromSuperview];
    
    _chatToolbar = chatToolbar;
    if (_chatToolbar) {
        [self.view addSubview:_chatToolbar];
    }
    
    CGRect tableFrame = self.tableView.frame;
    tableFrame.size.height = self.view.frame.size.height - _chatToolbar.frame.size.height;
    self.tableView.frame = tableFrame;
    if ([chatToolbar isKindOfClass:[EaseChatToolbar class]]) {
        [(EaseChatToolbar *)self.chatToolbar setDelegate:self];
//        self.chatBarMoreView = (EaseChatBarMoreView*)[(EaseChatToolbar *)self.chatToolbar moreView];
        self.faceView = (EaseFaceView*)[(EaseChatToolbar *)self.chatToolbar faceView];
        self.recordView = (EaseRecordView*)[(EaseChatToolbar *)self.chatToolbar recordView];
    }
}
- (void)setDataSource:(id<EaseMessageViewControllerDataSource>)dataSource
{
//    _dataSource = dataSource;
    
    [self setupEmotion];
}

#pragma mark - EMChatToolbarDelegate

- (void)chatToolbarDidChangeFrameToHeight:(CGFloat)toHeight
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = self.tableView.frame;
        rect.origin.y = 0;
        rect.size.height = self.view.frame.size.height - toHeight;
        self.tableView.frame = rect;
    }];
    
    [self _scrollViewToBottom:NO];
}

- (void)inputTextViewWillBeginEditing:(EaseTextView *)inputTextView
{
//    if (_menuController == nil) {
//        _menuController = [UIMenuController sharedMenuController];
//    }
//    [_menuController setMenuItems:nil];
}

- (void)didSendText:(NSString *)text
{
    
    if (text && text.length > 0) {
//        [self sendTextMessage:text];
//        [self.atTargets removeAllObjects];
        [self answerComment:text andType:@"1" andUrlLength:@"0"];

    }
}
- (void)didSendText:(NSString *)text withExt:(NSDictionary*)ext{
    
}



/*!
 @method
 @brief 设置表情
 @discussion 加载默认表情，如果子类实现了dataSource的自定义表情回调，同时会加载自定义表情
 @result
 */
- (void)setupEmotion
{
    if ([self.dataSource respondsToSelector:@selector(emotionFormessageViewController:)]) {
        NSArray* emotionManagers = [self.dataSource emotionFormessageViewController:self];
        [self.faceView setEmotionManagers:emotionManagers];
    } else {
        NSMutableArray *emotions = [NSMutableArray array];
        for (NSString *name in [EaseEmoji allEmoji]) {
            EaseEmotion *emotion = [[EaseEmotion alloc] initWithName:@"" emotionId:name emotionThumbnail:name emotionOriginal:name emotionOriginalURL:@"" emotionType:EMEmotionDefault];
            [emotions addObject:emotion];
        }
        EaseEmotion *emotion = [emotions objectAtIndex:0];
        EaseEmotionManager *manager= [[EaseEmotionManager alloc] initWithType:EMEmotionDefault emotionRow:3 emotionCol:7 emotions:emotions tagImage:[UIImage imageNamed:emotion.emotionId]];
        [self.faceView setEmotionManagers:@[manager]];
    }
}

- (void)didStartRecordingVoiceAction:(UIView *)recordView
{
    
    
    
//    if ([self.delegate respondsToSelector:@selector(messageViewController:didSelectRecordView:withEvenType:)]) {
//        [self.delegate messageViewController:self didSelectRecordView:recordView withEvenType:EaseRecordViewTypeTouchDown];
//    } else {
//        if ([self.recordView isKindOfClass:[EaseRecordView class]]) {
//            [(EaseRecordView *)self.recordView recordButtonTouchDown];
//        }
//    }
//    
    if ([self _canRecord]) {
        EaseRecordView *tmpView = (EaseRecordView *)recordView;
        tmpView.center = self.view.center;
        [self.view addSubview:tmpView];
        [self.view bringSubviewToFront:recordView];
        int x = arc4random() % 100000;
        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
        NSString *fileName = [NSString stringWithFormat:@"%d%d",(int)time,x];
        
        [[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:fileName completion:^(NSError *error)
         {
             if (error) {
                 NSLog(@"%@",NSEaseLocalizedString(@"message.startRecordFail", @"failure to start recording"));
             }
         }];
    }
}

- (void)didCancelRecordingVoiceAction:(UIView *)recordView
{
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
//    if ([self.delegate respondsToSelector:@selector(messageViewController:didSelectRecordView:withEvenType:)]) {
//        [self.delegate messageViewController:self didSelectRecordView:recordView withEvenType:EaseRecordViewTypeTouchUpOutside];
//    } else {
//        if ([self.recordView isKindOfClass:[EaseRecordView class]]) {
//            [(EaseRecordView *)self.recordView recordButtonTouchUpOutside];
//        }
//        [self.recordView removeFromSuperview];
//    }
}

#pragma 发送语音
- (void)didFinishRecoingVoiceAction:(UIView *)recordView andRecordPath:(NSString *)recordPath andDuration:(NSInteger)aDuration
{
    NSString *wavFilePath = [[recordPath stringByDeletingPathExtension]
                             stringByAppendingPathExtension:@"wav"];
    BOOL convertResult = [self convertAMR:recordPath toWAV:wavFilePath];
    if (convertResult){
        NSFileManager *fm = [NSFileManager defaultManager];
        [fm removeItemAtPath:recordPath error:nil];
        
    }else{
        
    }
    [self answerComment:wavFilePath andType:@"2" andUrlLength:[NSString stringWithFormat:@"%d",aDuration]];
}

- (BOOL)convertAMR:(NSString *)amrFilePath
             toWAV:(NSString *)wavFilePath
{
    BOOL ret = NO;
    BOOL isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:amrFilePath];
    if (isFileExists) {
        [EMVoiceConverter amrToWav:amrFilePath wavSavePath:wavFilePath];
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:wavFilePath];
        if (isFileExists) {
            ret = YES;
        }
    }
    
    return ret;
}



- (void)didDragInsideAction:(UIView *)recordView
{
    if ([self.recordView isKindOfClass:[EaseRecordView class]]) {
        [(EaseRecordView *)self.recordView recordButtonDragInside];
    }
}

- (void)didDragOutsideAction:(UIView *)recordView
{
    if ([self.recordView isKindOfClass:[EaseRecordView class]]) {
        [(EaseRecordView *)self.recordView recordButtonDragOutside];
    }
}

/*!
 @method
 @brief tableView滑动到底部
 @discussion
 @result
 */
- (void)_scrollViewToBottom:(BOOL)animated
{
    if (self.tableView.contentSize.height > self.tableView.frame.size.height)
    {
        CGPoint offset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
        [self.tableView setContentOffset:offset animated:animated];
    }
}
/*!
 @method
 @brief 当前设备是否可以录音
 @discussion
 @result
 */
- (BOOL)_canRecord
{
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                bCanRecord = granted;
            }];
        }
    }
    
    return bCanRecord;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
//    [[MyPlayTool sharePlayTool] stop];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"stopPlayVoiceNotification" object:nil];

}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
